const path = require("path");

const Koa = require("koa");

const { koaBody } = require("koa-body");

const parameter = require('koa-parameter')

const KoaStatic = require("koa-static");

const { koaSwagger } = require("koa2-swagger-ui");

const swagger = require("../utils/swagger");

const router = require("../router");
const errHandler = require("./errHandler");
const { respBean } = require("../middleware/respBean");

const app = new Koa();

app.use(respBean);

app.use(swagger.routes(), swagger.allowedMethods());

app.use(
  koaSwagger({
    routerPrefix: "/swagger",
    swaggerOptions: {
      url: "/swagger.json",
    },
  })
);

app.use(
  koaBody({
    multipart: true,
    formidable: {
      // uploadDir: path.join(__dirname, "../upload"),
      keepExtensions: true,
      maxFileSize: 200 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
    },
    parsedMethods: ["POST", "PUT", "PATCH", "DELETE"],
  })
);

app.use(KoaStatic(path.join(__dirname, "../upload")));

app.use(parameter(app))

app.use(router.routes()).use(router.allowedMethods());

// 统一错误处理
app.on("error", errHandler);

module.exports = app;
